                            # 10.1 从文件中读取数据
# 10.1.1 读取整个文件
with open('test_files/pi_digits.txt') as file_object:  # 函数open()打开文件，返回一个标识文件的对象
                                            # 在当前执行的文件所在的目录中查找指定的文件
                                            # 关键字with在不在需要访问文件后将其关闭
    contents = file_object.read()
    print(contents.rstrip() + "\n") # 方法rstrip()删除末尾空行

# 10.1.2 文件路径
    # 相对路径：with open('test_files/pi_digits.txt') as file_object
    # 绝对路径：file_path = r'D:\PycharmProjects\Chapter10\test_files\filename.txt'
    #           with open(file_path) as file_object
    # 在开头的单引号前加上r，区别转义字符
file_path = r'D:\PycharmProjects\Chapter10\test_files\pi_digits.txt'
with open(file_path) as file_object:
    contents = file_object.read()
    print(contents.rstrip() + "\n")
# 10.1.3 逐行读取
filename = 'test_files/pi_digits.txt'

with open(filename) as file_object:
    for line in file_object:
        print(line.rstrip())

    print("\n")
# 10.1.4 创建一个包含文件各行内容的列表
filename = 'test_files/pi_digits.txt'

with open(filename) as file_object:
    lines = file_object.readlines()  # 方法readlines()从文件读取每一行
                                     # 并将其存储到一个列表中
for line in lines:
    print(line.rstrip())
# 10.1.5 使用文件的内容
filename = 'test_files/pi_digits.txt'

with open(filename) as file_object:
    lines = file_object.readlines()

pi_string = ''
for line in lines:
    pi_string += line.strip() # 删除空格

print(pi_string)
print(len(pi_string))
# 10.1.6 包含一百万位的大型文件
filename = 'test_files/pi_million_digits.txt'

with open(filename) as file_object:
    lines = file_object.readlines()

pi_string = ''
for line in lines:
    pi_string += line.strip()

print(pi_string[:52] + "...")
print(len(pi_string))
# 10.1.7 圆周率值中包含你的生日吗
filename = 'test_files/pi_million_digits.txt'

with open(filename) as file_object:
    lines = file_object.readlines()

pi_string = ''
for line in lines:
    pi_string += line.strip()

birthday = input("Enter your birthday, in the form mmddyy: ")
if birthday in pi_string:
    print("Your birthday appears in the first million digits of pi!")
else:
    print("Your birthday does not appear in the first million digits of pi!")
                            # 10.2 写入文件
# 10.2.1 写入空文件
filename = 'test_files/programming.txt'

with open(filename, 'w') as file_object: # 'w'写入模式
    file_object.write("I love programming.\n")
# 10.2.2 写入多行
    file_object.write("I love creating new games.\n")
# 10.2.3 附加到文件
filename = 'test_files/programming.txt'

with open(filename, 'a') as file_object:    # 'a'追加模式
    file_object.write('I also love finding meaning in large datasets.\n')
    file_object.write('I love creating apps that can run in a browser.\n')
                            # 10.3 异常
# 10.3.1 处理ZeroDivisionError异常
try:
    print(5/0)
except ZeroDivisionError:
    print("You cannot divide by zero！")
# 10.3.2 使用try_except 代码块
print("Give me two numbers, and I'll divide them.")
print("Enter 'q' to quit.")

while True:
    first_number = input("\nFirst number: ")
    if first_number == 'q':
        break
    second_number = input("\nSecond number: ")
    if second_number == 'q':
        break
    try:
        answer = int(first_number) / int(second_number)
    except ZeroDivisionError:
        print("You can't divide by zero!")
    else:
        print(answer)
# 10.3.3 使用异常避免崩溃
# 10.3.4 else代码块
# 10.3.5 处理 FileNotFoundError 异常
filename = 'nonexistent.txt'

try:
    with open(filename) as file_object:
        contents = file_object.read()
except FileNotFoundError:
    msg = "Sorry, the file '" + filename + "' does not exist."
    print(msg)
# 10.3.6 分析文本
filename = 'test_files/alice.txt'

try:
    with open(filename) as f_obj:
        contents = f_obj.read()
except FileNotFoundError:
    msg = "Sorry, the file '" + filename + "' does not exist."
    print(msg)
else:
    # 计算文件大致包含多少单词
    words = contents.split()
    num_words = len(words)
    print("The file " + filename + " has about " + str(num_words) + " words.")
# 10.3.7 使用多个文件
def count_words(filename):
    """计算一个文本大致包含多少个单词"""
    try:
        with open(filename) as f_obj:
            contents = f_obj.read()
    except FileNotFoundError:
        msg = "Sorry, the file '" + filename + "' does not exist."
        print(msg)
    else:
        # 计算文件大致包含多少单词
        words = contents.split()
        num_words = len(words)
        print(
            "The file " + filename + " has about " + str(num_words) + " words.")

filenames = ['test_files/alice.txt', 'test_files/little_women.txt',
            'test_files/moby_dict.txt', 'test_files/siddhartha.txt', 'NONE.txt']
for filename in filenames:
    count_words(filename)
# 10.3.8 失败时一声不吭
def count_words(filename):
    """计算一个文本大致包含多少个单词"""
    try:
        with open(filename) as f_obj:
            contents = f_obj.read()
    except FileNotFoundError:
        pass    # 让编译器什么都不要做
    else:
        # 计算文件大致包含多少单词
        words = contents.split()
        num_words = len(words)
        print(
            "The file " + filename + " has about " + str(num_words) + " words.")

filenames = ['test_files/alice.txt', 'test_files/little_women.txt',
            'test_files/moby_dict.txt', 'test_files/siddhartha.txt', 'NONE.txt']
for filename in filenames:
    count_words(filename)
# 10.3.9 决定报告哪些错误
                            # 10.4 存储数据
# 10.4.1 使用json.dump()和json.load()
import json

password = 'password: 01260808xhwjhj'     # 用户想要存储的密码

filename = 'test_files/password.json'  # 文件存储的数据为JSON格式
with open(filename, 'w') as f_obj:  # 以写入模式打开
# 使用函数json.jump()将数据存储到文件password.json中
    json.dump(password, f_obj)

with open(filename) as f_obj:   # 以读取模式打开
# 使用函数json.load()加载存储在test_files/password.json中的信息
# 并将其存储在变量my_password中
    my_password = json.load(f_obj)

print(my_password)
# 10.4.2 保存和读取用户生成的数据
import json

# 如果以前存储了用户名，就加载它
# 否则，就提示用户输入用户名并存储它

filename = 'username.json'
try:
    with open(filename) as f_obj:
        username = json.load(f_obj)
except FileNotFoundError:
    username = input("What is your name? ")
    with open(filename, 'w') as f_obj:
        json.dump(username, f_obj)
        print("We'll remember you when you come back, " + username + "!")
else:
    print("Welcome back, " + username + "!")
# 10.4.3 重构
 # 重构代码如下：
import json

def get_stored_username():
    """如果存储了用户名，就获取它"""
    filename = 'username.json'
    try:
        with open(filename) as f_obj:
            username = json.load(f_obj)
    except FileNotFoundError:
        return None
    else:
        return username

def get_new_username():
    """提示用户输入用户名，存储并获取之"""
    username = input("What is your name? ")

    filename = 'username.json'
    with open(filename, 'w') as f_obj:
        json.dump(username, f_obj)

    return username

def greet_users():
    """问候用户，并指出其名字"""
    username = get_stored_username()
    if username != None:
        print("Welcome back, " + username + "!")
    else:
        username = get_new_username()
        print("We'll remember you when you come back, " + username + "!")

greet_users()
greet_users()